package com.dic.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dic.mall.product.service.CategoryBrandRelationService;
import com.dic.mall.product.vo.Catelog2Vo;
import com.google.common.base.Strings;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dic.common.utils.PageUtils;
import com.dic.common.utils.Query;

import com.dic.mall.product.dao.CategoryDao;
import com.dic.mall.product.entity.CategoryEntity;
import com.dic.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子树形结构
        List<CategoryEntity> collect = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return menu1.getSort()-menu2.getSort();
        }).collect(Collectors.toList());
        return collect;
    }

    List<CategoryEntity> getChildrens(CategoryEntity entity,List<CategoryEntity> entities){
        List<CategoryEntity> collect = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == entity.getCatId();
        }).map(menu->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
       //TODO 1.验证该菜单是否有关联

        //2.修改状态
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List allN() {
        List list = baseMapper.allN();
        System.out.println(list.size()+"jkjkjk");
        return null;
    }

    @Override
    public Long[] getCategoryPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = getParentPath(catelogId, path);
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);

    }

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if(!Strings.isNullOrEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("方法调用了");
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Map<String,  List<Catelog2Vo>> getCatalogJson() {
        //给缓存中放入json字符串，拿到的json字符串，还能逆转为需要的类型【序列化与反序列化】
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        //json跨语言跨平台
        String catalogJson = valueOperations.get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            System.out.println("index缓存未命中");
            //没有缓存，则查询数据库，并将结果json化，放入缓存
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDBWithRedisLock();
            return catalogJsonFromDB;
        }
        System.out.println("index缓存命中");
        //有缓存，则将json反序列化，返回
        Map<String, List<Catelog2Vo>> stringListMap =
                JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        return stringListMap;
    }

    public Map<String,  List<Catelog2Vo>> getCatalogJsonFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Boolean lock = valueOperations.setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("占锁成功");
            //占锁成功，执行业务
            Map<String, List<Catelog2Vo>> catalogFromDB = getCatalogFromDB();
            //执行业务结束，释放锁
            //获取值对比+删除锁=原子操作 lua脚本解锁
            String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0  end";
            stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            String lockValue = valueOperations.get("lock");
            if (uuid.equals(lockValue)) {
                stringRedisTemplate.delete("lock");
            }
            return catalogFromDB;
        } else {
            //自旋方式
            try {
                System.out.println("占锁失败。。。等待重试");
                Thread.sleep(200);
            } catch (Exception e) {
            }
            return getCatalogJsonFromDBWithRedisLock();
        }
    }

    public Map<String,  List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock() {
        RLock rLock = redissonClient.getLock("catalogJson");
        rLock.lock();
        //占锁成功，执行业务
        Map<String, List<Catelog2Vo>> catalogFromDB = getCatalogFromDB();
        //执行业务结束，释放锁
        rLock.unlock();
        return catalogFromDB;
    }

    private Map<String, List<Catelog2Vo>> getCatalogFromDB() {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        String catalogJson = valueOperations.get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)) {
            System.out.println("查询了缓存");
            //有缓存，则将json反序列化，返回
            Map<String, List<Catelog2Vo>> stringListMap =
                    JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                    });
            return stringListMap;
        }
        System.out.println("查询了数据库");
        //查询所有菜单
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查询一级菜单
        List<CategoryEntity> level1Categorys = getMenuByParentId(selectList, 0L);
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v1 -> {
            //2.查询二级菜单
            List<CategoryEntity> level2Categorys = getMenuByParentId(selectList, v1.getCatId());
            List<Catelog2Vo> collect = null;
            if (level2Categorys != null) {
                collect = level2Categorys.stream().map(v2 -> {
                    //3.查询三级菜单
                    List<CategoryEntity> entities = getMenuByParentId(selectList, v2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> formatCatelog3Vo = null;
                    if (entities != null) {
                        formatCatelog3Vo = entities.stream().map(v3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(v2.getCatId().toString(), v3.getCatId().toString(), v3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v1.getCatId().toString(), formatCatelog3Vo, v2.getCatId().toString(), v2.getName());
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        String jsonString = JSON.toJSONString(parent_cid);
        valueOperations.set("catalogJson", jsonString);
        return parent_cid;
    }

    public Map<String,  List<Catelog2Vo>> getCatalogJsonFromDBWithLocalLock() {
        synchronized (this){
            ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
            return getCatalogFromDB();
        }
    }

    private List<CategoryEntity> getMenuByParentId( List<CategoryEntity> selectList,Long parent_id) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid().equals(parent_id);
        }).collect(Collectors.toList());
        return collect;
    }


    private List<Long> getParentPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        Long parentCid = categoryEntity.getParentCid();
        if(parentCid!=0){
            getParentPath(parentCid,path);
        }
        return path;
    }
}